//
//  DeployWiFiView.m
//  TaiHao
//
//  Created by rzm on 16/6/2.
//  Copyright © 2016年 rzm. All rights reserved.
//

#import "SampuxDeployWiFiView.h"
#import "AFHTTPSessionManager.h"
#import "NSString+MD5.h"
#import "BrowserBonjour.h"
#import "SPWifiModel.h"
#import "AsyncSocket.h"
#import "SampuxLoadView.h"


#define kWebServiceType @"_easylink._tcp"
#define kInitialDomain  @"local"

#define WIFIKEY @"WIFIKEY"

@interface SampuxDeployWiFiView ()<EasyLinkFTCDelegate,BrowserBonjourDelegate,UITextFieldDelegate,UIAlertViewDelegate>
{
    UIAlertView *m_alert;
    NSTimer *timer;
    NSString *keyString;
    NSMutableDictionary *_aLinkDict;
    NSInteger count;
    
}
@property (nonatomic, strong) UITextField *wifiNameF ;
@property (nonatomic, strong) UITextField *passWordF ;
@property (nonatomic, strong) UIButton *btn ;

@property (nonatomic, copy) NSString *product_id;
@property (nonatomic, copy) NSString *product_key;

@property (nonatomic, copy) NSString *device_id;
@property (nonatomic, copy) NSString *device_token;
/*********************Mdns发现的设备列表*************************/
@property(strong,nonatomic)UILabel     *m_section;//待绑定设备文字
@property(strong,nonatomic)UITableView *m_tableview;//设备列表
@property(strong,nonatomic)NSMutableArray  *m_services;//发现服务
@property(strong,nonatomic)BrowserBonjour  *m_mdns;//bonjour接口
@property (nonatomic, strong) NSMutableDictionary *wlanConfig ;

@property(nonatomic,assign) BOOL isSuccessOrNot;
@property (nonatomic, strong) SPWifiModel *wifiModel;

@property (nonatomic, copy) NSString *passwordString ;
@property (nonatomic, copy) NSString *ssidString ;
@property (nonatomic, assign , getter=needSaveWifi) BOOL saveWifi;


@end

@implementation SampuxDeployWiFiView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame: frame]) {
        self.btn.userInteractionEnabled = YES;
        _aLinkDict = [NSMutableDictionary dictionary];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptPosses:) name:NOTIFICATION_RESPONSE_POSSESSOR object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshWiFiName:) name:@"getWiFiNameWithSetWiFi" object:nil];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getFail) name:@"socketConnectFail" object:nil];

        self.isProgressIng = NO;
        _wlanConfig = [NSMutableDictionary dictionaryWithCapacity:20];
        [self loadUI];
    }
    return self;
}

//- (void)getFail
//{
//    if (self.progressBlock) {
//        self.progressBlock(YES);
//    }
//    self.btn.userInteractionEnabled = NO;
//}

- (void)refreshWiFiName:(NSNotification *)notification
{
//    [m_easylink_config stopTransmitting];
//    m_easylink_config = nil;
//    [self getSSID];
}

- (void)loadUI
{
    CGFloat font;
    if (IS_IPHONE_4_OR_LESS) {
        font = 14.;
    } else if (IS_IPHONE_5_OR_LESS) {
        font = 14.;
    } else if (IS_IPHONE_6) {
        font = 16.;
    } else {
        font = 17.;
    }
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, self.width, self.height - 64)];
    [self addSubview:backView];
    [backView setCorner:5];
    backView.backgroundColor = THSystemClearColor;
    
    UIView *bView = [[UIView alloc]init];
    [backView addSubview:bView];
    bView.frame = CGRectMake(0, Sampux6HScale(20), backView.width, backView.height *0.15);
    
    CGSize maxSize = CGSizeMake(MAXFLOAT, bView.height);
    NSString *agreementStr = @"请确保手机和设备在同一WiFi下";
    CGSize Size = [SampuxGlobalTool getSizeWithString:agreementStr andFont:THFont(font) andMaxSize:maxSize];
    
    UILabel *label = [UILabel createLabelWithFrame:CGRectMake(0, bView.height/2 - maxSize.height/2, backView.width, bView.height) textColor:THWhiteAlplaColor(0.8) font:[UIFont systemFontOfSize:font]];
    [bView addSubview:label];
    label.textAlignment = NSTextAlignmentRight;
    label.text = @"请确保手机和设备在同一WiFi下";
    label.width = Size.width;
    
    CGSize wmaxSize = CGSizeMake(MAXFLOAT, bView.height);
    CGSize wSize = [SampuxGlobalTool getSizeWithString:@"去设置" andFont:THFont(font) andMaxSize:wmaxSize];
    CGSize hmaxSize = CGSizeMake(wSize.width, MAXFLOAT);
    CGSize hSize = [SampuxGlobalTool getSizeWithString:@"去设置" andFont:THFont(font) andMaxSize:hmaxSize];
    
    UIButton *setWiFiBtn = [UIButton createButtonWithTitle:@"去设置" frame: CGRectMake(label.right + 5, bView.height/2 - hSize.height/2, wSize.width + 30, hSize.height) titleFont:THFont(font) titleColor:THDeFaultBlueColor];
    [setWiFiBtn setCorner:setWiFiBtn.height/2];
    [bView addSubview:setWiFiBtn];
    [setWiFiBtn addTarget:self action:@selector(setWiFibtnClick) forControlEvents:UIControlEventTouchUpInside];
    setWiFiBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [setWiFiBtn setImage:imageNamed(@"setToWiFi") forState:UIControlStateNormal];
    setWiFiBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 5 , 0, 0);
    setWiFiBtn.hitTestEdgeInsets = UIEdgeInsetsMake( - 10, - 10, - 10,  - 10);
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(setWiFiBtn.x, setWiFiBtn.bottom, setWiFiBtn.width, 1)];
    [bView addSubview:lineView];
    lineView.backgroundColor  = THDeFaultBlueColor;
    
    bView.width = label.width + setWiFiBtn.width;
    bView.frame = CGRectMake(backView.width/2 - bView.width/2, Sampux6HScale(20), backView.width, backView.height *0.15);

    
    _wifiNameF = [UITextField createTextFieldWithRect:CGRectMake(backView.width/2 - Sampux6WScale(SampuxCustomW)/2, label.bottom + Sampux6HScale(30), Sampux6WScale(SampuxCustomW), Sampux6HScale(SampuxCustomH)) andPlaceholder:@"请输入WiFi" andLeftImage:@"wifi"];
    [backView addSubview:_wifiNameF];
    [UIView createLineViewInbottom:_wifiNameF];
    _wifiNameF.delegate = self;
    _wifiNameF.keyboardType = UIKeyboardTypeASCIICapable;

    _passWordF = [UITextField createTextFieldWithRect:CGRectMake(_wifiNameF.x, _wifiNameF.bottom + SampuxMargin, _wifiNameF.width, _wifiNameF.height) andPlaceholder:@"请输入WiFi密码" andLeftImage:@"lock"];
    [backView addSubview:_passWordF];
    [UIView createLineViewInbottom:_passWordF];
    _passWordF.delegate = self;
    _passWordF.keyboardType = UIKeyboardTypeASCIICapable;
    _passWordF.secureTextEntry = YES;
    
    [self getSSID];

    
    UIButton *btn = [UIButton createButtonWithTitle:@"下一步" frame: CGRectMake(backView.width/2 - Sampux6WScale(345/2)/2, _passWordF.bottom + Sampux6HScale(30) , Sampux6WScale(345/2), Sampux6HScale(SampuxCustomH)) titleFont:THFont(font) titleColor:THDeFaultBlueColor];
    [btn setCorner:btn.height/2];
    btn.layer.borderWidth = 1;
    btn.layer.borderColor = THWhiteAlplaColor(0.6).CGColor;
    [backView addSubview:btn];
    [btn addTarget:self action:@selector(nextStepClick) forControlEvents:UIControlEventTouchUpInside];
    self.btn = btn;
    
}

- (void)getSSID
{
    self.userInteractionEnabled = YES;
    _wlanConfig = [NSMutableDictionary dictionary];
    if( m_easylink_config == nil)
    {
        m_easylink_config = [[EASYLINK alloc]initForDebug:false WithDelegate:self];
        
        //        m_easylink_config = [[EASYLINK alloc]initWithDelegate:self];
    }
    self.wifiModel = [[SPWifiModel alloc] init];
    self.saveWifi = YES;
    /*路由器ssid*/
    self.ssidString = [EASYLINK ssidForConnectedNetwork];
    _wifiNameF.text = self.ssidString;
    self.wifiModel.wifiName = self.ssidString;
    [self handlePassword];
    //    NSString *passwordString = @"gaupu2014";/*路由器密码*/
}
/**
 *  遍历NSUserDefault查找有没有ssid存在
 */
- (void)handlePassword
{
    NSMutableArray *array = [self getWIFIDic];
    __weak typeof(SampuxDeployWiFiView *) wSelf = self;
    if (array.count) {
        [array enumerateObjectsUsingBlock:^(SPWifiModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.wifiName isEqualToString:self.ssidString]) {
                wSelf.passWordF.text = obj.password;
                wSelf.passwordString = obj.password;
                wSelf.wifiModel.password = obj.password;
                wSelf.saveWifi = NO;
                *stop = YES;
            }
        }];
    }
}

- (void)saveWIFIWithDic:(NSArray *)wifiArray
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSData *tokenObject = [NSKeyedArchiver archivedDataWithRootObject:wifiArray];
    [userDefaults setObject:tokenObject forKey:WIFIKEY];
    [userDefaults synchronize];
}

- (NSMutableArray *)getWIFIDic
{
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:WIFIKEY];
    NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return array;
}

- (void)nextStepClick
{
    count = 0;
//     如果[self getWIFIDic]返回的数组为空的时候，存储ssid对应的密码
//    self.userInteractionEnabled = NO;
//    if (self.progressBlock) {
//        self.progressBlock(YES);
//    }
    self.passwordString = _passWordF.text;/*路由器密码*/
    if ([self getWIFIDic].count == 0) {
        self.wifiModel.password = _passWordF.text;
    }
    
    m_easylink_config.delegate = self;
    NSData *ssidData = [EASYLINK ssidDataForConnectedNetwork];
    NSData *numberData =[self.numberStr dataUsingEncoding:NSUTF8StringEncoding];
    [_wlanConfig setObject:ssidData forKey:KEY_SSID];//NSData类型
    [_wlanConfig setObject:_passWordF.text forKey:KEY_PASSWORD];
    [_wlanConfig setObject: @YES forKey:KEY_DHCP];
    
    [m_easylink_config prepareEasyLink_withFTC:_wlanConfig info:numberData mode:EASYLINK_V2_PLUS];
    [m_easylink_config transmitSettings];//开始发包了
    [self loadViewShow];
    timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(judgeIsSuccess) userInfo:nil repeats:NO];
}

- (SampuxLoadView *)loadView
{
    if (_loadView == nil) {
        _loadView = [[SampuxLoadView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    }
    return _loadView;
}

- (void)loadViewShow
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [delegate.window addSubview:self.loadView];
}

- (void)setWiFibtnClick
{
    if (IOS10Later) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {}];
        }
    } else {

        NSURL *url = [NSURL URLWithString:@"prefs:root=WIFI"];
        if ([[UIApplication sharedApplication] canOpenURL:url])
        {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

- (void)judgeIsSuccess
{
    count = 0;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.loadView removeFromSuperview];
        
    });//    self.btn.userInteractionEnabled = YES;
//
//    self.userInteractionEnabled = YES;
//    if (self.progressBlock) {
//        self.progressBlock(NO);
//    }

    self.isSuccessOrNot = NO;
    if (timer.valid) {
        [timer invalidate];
        timer = nil;
    }
    self.nextFailBlock(self.numberStr);
    [[NSNotificationCenter defaultCenter]postNotificationName:@"addEqiupMentFail" object:self.numberStr];
}

- (void)setIsSuccessOrNot:(BOOL)isSuccessOrNot
{
    _isSuccessOrNot = isSuccessOrNot;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.loadView removeFromSuperview];
        
    });
    
    self.saveWifi = YES;
    _wifiModel.wifiName = self.wifiNameF.text;
    _wifiModel.password = self.passWordF.text;
    
    if (self.needSaveWifi) {
        NSMutableArray *array = [NSMutableArray arrayWithArray:[self getWIFIDic]];
        [array removeAllObjects];
        [array addObject:self.wifiModel];
        [self saveWIFIWithDic:array];
    }
    
//    if (_isSuccessOrNot == YES) {
//        if (self.needSaveWifi) {
//            NSMutableArray *array = [NSMutableArray arrayWithArray:[self getWIFIDic]];
//            [array removeAllObjects];
//            [array addObject:self.wifiModel];
//            [self saveWIFIWithDic:array];
//        }
//    }else {
//        NSMutableArray *array = [self getWIFIDic];
//        __weak typeof(SampuxDeployWiFiView *) wSelf = self;
//        if (array.count) {
//            __block NSInteger index;
//            [array enumerateObjectsUsingBlock:^(SPWifiModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                if ([obj.wifiName isEqualToString:self.ssidString]) {
//                    index = idx;
//                    *stop = YES;
//                }
//            }];
//            if (index != -1) {
////                [array removeObjectAtIndex:index];
//                [self saveWIFIWithDic:array];
//            }
//        }
//    }
}

- (void)setNumberStr:(NSString *)numberStr
{
    _numberStr = numberStr;
}
//停掉EasyLink
//-(void)stopLink
//{
//    [m_easylink_config stopTransmitting];
//    [m_easylink_config unInit];
//    m_easylink_config = nil;
//}
#pragma mark - EasyLink delegate -

- (void)onFound:(NSNumber *)client withName:(NSString *)name mataData:(NSDictionary *)mataDataDict
{
    [m_easylink_config stopTransmitting];
    m_easylink_config = nil;
}

- (void)onFoundByFTC:(NSNumber *)ftcClientTag withConfiguration: (NSDictionary *)configDict
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.loadView removeFromSuperview];
        
    });
//    self.btn.userInteractionEnabled = YES;
//    self.userInteractionEnabled = YES;
//    if (self.progressBlock) {
//        self.progressBlock(NO);
//    }
    self.isSuccessOrNot = YES;
    NSDictionary *CDict = [configDict objectForKey:@"C"][1];
    NSArray *cArr = [CDict objectForKey:@"C"];
    
    for (int i = 0; i < cArr.count; i ++) {
        NSDictionary *cDict = cArr[i];
        if ([[cDict objectForKey:@"N"] isEqualToString:@"Master Key"]) {
            keyString = [NSString stringWithFormat:@"%@%@",self.numberStr,[cDict objectForKey:@"C"]];
        }
    }
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"cloud.sampux.com",@"SPP Server",@63301,@"SPP Server Port", nil];
    [m_easylink_config configFTCClient:ftcClientTag withConfiguration:dic];
    count = 1;
    [GBInterMaster_CommForSystem requestAcceptPossessor:0 withDeviceKey:keyString];
    
    if (timer.isValid) {
        [timer invalidate];
        timer = nil;
    }

}

#pragma mark - EasyLink delegate -
- (void)onDisconnectFromFTC:(NSNumber *)ftcClientTag
{
    NSLog(@"Device disconnected!");
    if (self.nextFailBlock) {
        self.nextFailBlock(self.numberStr);
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_passWordF resignFirstResponder];
    [_wifiNameF resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self layoutIfNeeded];
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight );
    return YES;
}

- (void)acceptPosses:(NSNotification *)notification
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.loadView removeFromSuperview];
    });

//    self.userInteractionEnabled = YES;
//    if (self.progressBlock) {
//        self.progressBlock(NO);
//    }
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@" acceptPosses == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0x00){
//        [[NSUserDefaults standardUserDefaults] setObject:self.numberStr forKey:@"account"];
        self.nextSuccessBlock(self.numberStr);
    } else {
        if (count == 1) {
            dispatch_async(dispatch_get_main_queue(), ^{
              
                m_alert = [[UIAlertView alloc]initWithTitle:nil message:[SPResponseCodePrompt responseCodePrompt:responseCode] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                m_alert.delegate = self;
                [m_alert show];
                count = 0;
            });
            [[NSNotificationCenter defaultCenter]postNotificationName:@"addEqiupMentFail" object:self.numberStr];
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"%ld",(long)buttonIndex);
    if (buttonIndex == 0) {
        
    } else {
        self.nextListBlock();
    }
}

- (void)dealloc
{
    if (timer.isValid) {
        [timer invalidate];
        timer = nil;
    }
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
